<%@page import="java.awt.image.DataBufferUShort"%>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.yuxin.common.util.*" %>
<%@ page import="com.yuxin.core.TransactionManager" %>
<%@ page import="java.net.URLEncoder"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="java.text.DecimalFormat" %>
<%@ page import="java.util.*" %>

<%
    String action = request.getParameter("action");
    response.setContentType("text/html;charset=UTF-8");
    Connection conn = DBUtil.getConnection();
    TransactionManager transaction = new TransactionManager(conn);
    String ctx = request.getContextPath();
    StringBuffer html = new StringBuffer(128);
    try{
        if("login".equals(action)){// 登录
            transaction.begin();
            Map result = new HashMap();
            try {
                String name = request.getParameter("USERNAME");
                String password = request.getParameter("PASSWORD");
                Map<String,Object> user = DBUtil.queryUniqueResult(conn, "SELECT ID,SRC_ID,USERNAME,PASSWORD FROM P_USER WHERE TYPE = '1' AND USERNAME = ? " ,name);
                if(user != null){
                    String pwd = user.get("PASSWORD").toString();
                    if(!MD5Util.encodePassword(name+password).equals(pwd)){
                        throw new RuntimeException("密码错误！");
                    }
                    int age = 30*24*3600;
                    CommonUtil.setCookie(response,"TICKET",user.get("SRC_ID").toString(),age,ctx+"/site");
                }else{
                    throw new RuntimeException("帐号不存在!");
                }
                result.put("isSuccess",true);
            }catch (Exception e){
                result.put("isSuccess",false);
                result.put("error",e.getMessage());
                throw new RuntimeException(e);
            }finally {
                html.append(JsonUtil.convertString(result));
            }
        }else if("register".equals(action)){// 注册
            transaction.begin();
            Map result = new HashMap();
            try {
                String name = request.getParameter("USERNAME");
                String pwd = request.getParameter("PASSWORD");
                int count = DBUtil.count(conn,"SELECT * FROM P_USER WHERE USERNAME = ? ",name);
                if(count > 0){
                   throw new RuntimeException("该帐号已存在！");
                }
                Map creditData = new HashMap<String,String>();
                creditData.put("ID",UUIDUtil.getUUID());
                DBUtil.save(conn, creditData, "P_CREDIT_USER");
                Map userData = new HashMap<String,String>();
                userData.put("ID",UUIDUtil.getUUID());
                userData.put("USERNAME",name);
                userData.put("SRC_ID",creditData.get("ID"));
                userData.put("PASSWORD",MD5Util.encodePassword(name+pwd));
                userData.put("TYPE","1");
                DBUtil.save(conn, userData, "P_USER");
                result.put("isSuccess",true);
            }catch (Exception e){
                result.put("isSuccess",false);
                result.put("error",e.getMessage());
                throw new RuntimeException(e);
            }finally {
                html.append(JsonUtil.convertString(result));
            }
        }else if("saveProdOrder".equals(action)){//保存订单
            transaction.begin();
            Map result = new HashMap();
            try {
                String shangpin = request.getParameter("shangpin");
                String shangpinsl = request.getParameter("shangpinsl");
                String shangpinjg = request.getParameter("shangpinjg");
                // 创建商品订单信息
                Map  shanpindd = new HashMap<String,String>();
                shanpindd.put("CREDIT_ID",CommonUtil.getCookie(request,"TICKET"));
                shanpindd.put("STATUS","1");
                shanpindd.put("TOTAL_PRICE",0);
                // 保存订单与商品之间的关系
                String[] shangpinArr = shangpin.split(";");
                String[] shangpinslArr = shangpinsl.split(";");
                String[] shangpinjgArr = shangpinjg.split(";");
				//查询商家
                Map<String,String> tradesMap = new HashMap();
                for(int i=0,len=shangpinArr.length;i<len;i++){
                    Map goods = DBUtil.queryUniqueResult(conn,"SELECT TRADE_ID FROM P_GOODS WHERE ID = ? ",shangpinArr[i]);
                    String tradeId = goods.get("TRADE_ID").toString();
                    if(StringUtils.hasText(tradesMap.get(tradeId))){
                    	double total = Double.parseDouble(tradesMap.get(tradeId)) + Double.parseDouble(shangpinjgArr[i]);
                    	tradesMap.put(tradeId,String.valueOf(total));
                    }else{
                    	tradesMap.put(tradeId,shangpinjgArr[i]);
                    }
                }
       			Set set = tradesMap.keySet();
       			Iterator it = set.iterator();
       			while(it.hasNext()){
       				String tradeId = it.next().toString();
       				String orderId = UUIDUtil.getUUID();
                    shanpindd.put("ID",orderId);
                    shanpindd.put("CODE",System.nanoTime());
                    shanpindd.put("TRADE_ID",tradeId);
                    shanpindd.put("TOTAL_PRICE",tradesMap.get(tradeId));
       				tradesMap.put(tradeId,orderId);
                	DBUtil.save(conn,shanpindd,"P_ORDERS");
       			}
                Map proOrderProduct = new HashMap<String, String>();
                for(int i=0,len=shangpinArr.length;i<len;i++){
                    proOrderProduct.put("ID",UUIDUtil.getUUID());
                    Map goods = DBUtil.queryUniqueResult(conn,"SELECT TITLE,TITLE_IMG,TRADE_ID FROM P_GOODS WHERE ID = ? ",shangpinArr[i]);
                    proOrderProduct.put("ORDER_ID",tradesMap.get(goods.get("TRADE_ID")));
                    proOrderProduct.put("GOODS_ID",shangpinArr[i]);
                    proOrderProduct.put("GOODS_NAME",goods.get("TITLE"));
                    proOrderProduct.put("GOODS_IMG",goods.get("TITLE_IMG"));
                    proOrderProduct.put("GOODS_NUMBER",shangpinslArr[i]);
                    proOrderProduct.put("GOODS_PRICE",shangpinjgArr[i]);
                    DBUtil.save(conn,proOrderProduct,"P_ORDER_GOODS");
                }
                result.put("isSuccess",true);
            }catch (Exception e){
                result.put("isSuccess",false);
                result.put("error",e.getMessage());
                throw new RuntimeException(e);
            }finally {
                html.append(JsonUtil.convertString(result));
            }
		}else if("favorite".equals(action)){//收藏
            transaction.begin();
            Map result = new HashMap();
            try {
            	String id = request.getParameter("id");
                int count = DBUtil.count(conn,"SELECT * FROM P_FAVORITE WHERE GOODS_ID = ? ",id);
                if(count > 0){
                   throw new RuntimeException("已收藏！");
                }
                Map fav = new HashMap<String,String>();
                fav.put("ID",UUIDUtil.getUUID());
                fav.put("CREDIT_ID",CommonUtil.getCookie(request,"TICKET"));
                fav.put("GOODS_ID",id);
            	DBUtil.save(conn,fav,"P_FAVORITE");
                result.put("isSuccess",true);
            }catch (Exception e){
                result.put("isSuccess",false);
                result.put("error",e.getMessage());
                throw new RuntimeException(e);
            }finally {
                html.append(JsonUtil.convertString(result));
            }
		}
    }catch (Exception e){
        transaction.rollback();
        e.printStackTrace();
    }finally {
        transaction.commit();
        DBUtil.close(conn);
        out.clear();
        response.getWriter().write(html.toString());
        out = pageContext.pushBody();
    }
%>